package groupManagement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Timer;

import javax.jms.JMSException;
import javax.jms.TopicSubscriber;

import chat.LingvoChat;

import topicHandlers.Control;
import topicHandlers.Translate;



public class ChatGroup {
		
	private HashSet<String> userNames;
	private String groupName;
	private String userName;
	private Timer aliveSender;
	private TopicSubscriber translate;
	private TopicSubscriber control;
	
	public ChatGroup(String groupName,String userName,String lang) {
		super();
		this.userNames = new HashSet<String>();
		this.groupName = groupName;
		this.userName=userName;
		//start the I'm alive sender
		Timer timer=new Timer();
		timer.scheduleAtFixedRate(new AliveSender(groupName, userName, lang), 0, 10000);
		this.aliveSender=timer;
		this.translate=LingvoChat.initListner(groupName, new Translate(lang));
		this.control=LingvoChat.initListner(groupName+"-control", new Control(groupName, this,userName,lang));
		this.userNames.add(userName);
		User.addUserToGroup(userName, lang, this);
		LingvoChat.publishMsg(groupName+"-control", "join-" + lang + "-" + userName);
	}
	
	//clean up all of the timers and listeners.
	public void leaveGroup(){
		this.aliveSender.cancel();
		try {
			this.translate.close();
			this.control.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		for(String user : userNames){
			User.removeUserFromGroup(user, this);
		}
		LingvoChat.publishMsg(groupName+"-control", "leave-" + userName);
	}
	
	public void addUser(String userName,String lang)
	{
		synchronized (userNames) {
			User.addUserToGroup(userName, lang, this);
			userNames.add(userName);
		}
	}
	public  void removeUser(String userName){
		synchronized (userNames) {
			if(userNames.contains(userName)){
				userNames.remove(userName);
				User.removeUserFromGroup(userName, this);
			}
		}
	}

	public boolean doYouHaveThisUser(String userName){
		synchronized (userNames) {
			return (userNames.contains(userName));
		}
	}


	public void printStatus() {
		System.out.println("~~~" + this.groupName.substring(14) + "~~~");
		synchronized (userNames) {
			for(String user : userNames){
				User.printUser(user);
			}
		}
		System.out.println("");
	}
	
}
